#define _CRT_SECURE_NO_DEPRECATE
#pragma comment(lib,"Ws2_32.lib" )
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 使用 winsock2.h 替代 winsock.h
#include <winsock2.h> 
#define SIZE 1024

void send_file(FILE* fp, int sockfd) {
    int n;
    char data[SIZE] = { 0 };

    while (fgets(data, SIZE, fp) != NULL) {
        // 计算实际读取的数据长度
        n = strlen(data); 
        // 使用实际数据长度发送数据
        n = send(sockfd, data, n, 0); 
        if (n == SOCKET_ERROR) {
            // 修正端口号信息
            printf("服务器 127.0.0.1:8081 失去连接\n"); 
            exit(1);
        }
        ZeroMemory(data, SIZE);
    }
}

void start()
{
    // 使用 C 语言初始化方式
    WORD version = 0; 
    WSADATA wsadata;
    int socket_return = 0;
    version = MAKEWORD(2, 0);
    socket_return = WSAStartup(version, &wsadata);
    if (socket_return != 0)
        exit(0);
}

int main() {
    start();
    char ip[] = "127.0.0.1";
    int port = 8081;
    int e;
    int sockfd;
    struct sockaddr_in server_addr;
    FILE* fp;
    char filename[] = "send.txt";

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("[-]Error in socket");
        exit(1);
    }
    printf("[+]Server socket created successfully.\n");

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port); // 添加htons转换端口
    server_addr.sin_addr.s_addr = inet_addr(ip);

    e = connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if (e == -1) {
        // 修正端口号信息
        printf("服务器 127.0.0.1:8081 失去连接\n"); 
        exit(1);
    }
    printf("[+]Connected to Server.\n");

    fp = fopen(filename, "r");
    if (fp == NULL) {
        perror("[-]Error in reading file.");
        exit(1);
    }

    send_file(fp, sockfd);
    printf("[+]File data sent successfully.\n");
    printf("[+]Closing the connection.\n");
    closesocket(sockfd);
    // 清理 Winsock 库
    WSACleanup(); 

    return 0;
}
